package com.jl15988.simpletools.common.utils;

import com.jl15988.simpletools.common.exception.BusinessException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT令牌工具类
 *
 * @author jl15988
 */
@Component
public class TokenUtils {

    private static String secret;
    private static Long expiration;

    @Value("${jwt.secret}")
    public void setSecret(String secret) {
        TokenUtils.secret = secret;
    }

    @Value("${jwt.expiration}")
    public void setExpiration(Long expiration) {
        TokenUtils.expiration = expiration;
    }

    /**
     * 从请求中获取用户ID
     *
     * @param request HTTP请求
     * @return 用户ID
     */
    public static Long getUserId(HttpServletRequest request) {
        Claims claims = getClaimsFromRequest(request);
        if (claims == null) {
            throw new BusinessException("用户未登录");
        }
        return Long.parseLong(claims.getSubject());
    }

    /**
     * 从请求中获取用户名
     *
     * @param request HTTP请求
     * @return 用户名
     */
    public static String getUsername(HttpServletRequest request) {
        Claims claims = getClaimsFromRequest(request);
        if (claims == null) {
            throw new BusinessException("用户未登录");
        }
        return claims.get("username", String.class);
    }

    /**
     * 从请求中获取Claims
     *
     * @param request HTTP请求
     * @return Claims对象
     */
    private static Claims getClaimsFromRequest(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            return null;
        }
        token = token.substring(7);
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 生成JWT令牌
     *
     * @param userId 用户ID
     * @param username 用户名
     * @return JWT令牌
     */
    public static String generateToken(Long userId, String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", username);
        return createToken(claims, userId.toString());
    }

    /**
     * 创建JWT令牌
     *
     * @param claims 声明
     * @param subject 主题
     * @return JWT令牌
     */
    private static String createToken(Map<String, Object> claims, String subject) {
        Date now = new Date();
        Date expirationDate = new Date(now.getTime() + expiration * 1000);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }
} 